package com.zero2oneit.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zero2oneit.mall.common.annotion.RepeatSubmit;
import com.zero2oneit.mall.common.bean.auth.AppWxLoginObject;
import com.zero2oneit.mall.common.bean.auth.RegisterInfo;
import com.zero2oneit.mall.common.bean.member.*;
import com.zero2oneit.mall.common.query.member.InfoQueryObject;
import com.zero2oneit.mall.common.utils.JwtUtils;
import com.zero2oneit.mall.common.utils.R;
import com.zero2oneit.mall.common.utils.StringUtils;
import com.zero2oneit.mall.common.utils.WxQrCode;
import com.zero2oneit.mall.common.utils.bootstrap.BoostrapDataGrid;
import com.zero2oneit.mall.member.config.WxAuthProperties;
import com.zero2oneit.mall.member.feign.CouponFeign;
import com.zero2oneit.mall.member.feign.OssFeign;
import com.zero2oneit.mall.member.mapper.MemberAccountsMapper;
import com.zero2oneit.mall.member.mapper.MemberFansMapper;
import com.zero2oneit.mall.member.mapper.MemberInfoMapper;
import com.zero2oneit.mall.member.mapper.MemberLeadersMapper;
import com.zero2oneit.mall.member.service.MemberAccountsService;
import com.zero2oneit.mall.member.service.MemberFansService;
import com.zero2oneit.mall.member.service.MemberInfoService;
import com.zero2oneit.mall.member.service.MemberLeadersService;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class MemberInfoServiceImpl extends ServiceImpl<MemberInfoMapper, MemberInfo> implements MemberInfoService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberAccountsService memberAccountsService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private MemberLeadersService memberLeadersService;
    @Autowired
    private MemberFansService memberFansService;
    @Autowired
    private OssFeign ossFeign;
    @Autowired
    private CouponFeign couponFeign;
    @Autowired
    private MemberFansMapper memberFansMapper;
    @Autowired
    private MemberLeadersMapper memberLeadersMapper;
    @Autowired
    private MemberAccountsMapper memberAccountsMapper;
    @Autowired
    WxAuthProperties wxAuthBean;
    @Override
    public Boolean sendMsg(Map<String,String> verifyMap) {
        Map<String,String> map =new HashMap<>();
        String content= String.valueOf((int)((Math.random()*9+1)*100000));
        String phone=verifyMap.get("phone");
        String value="";
        map.put("phone",phone);
        map.put("content",content);
        amqpTemplate.convertAndSend("mall.sms.exchange", "sms.info.update",map);
        if (verifyMap.get("type").equals("0")){
            value="member:InfoUpdate:phone:"+phone;
        }else if (verifyMap.get("type").equals("1")){
            value="member:InfoUpdate:pay:"+phone;
        }
        redisTemplate.opsForValue().set(value,content,300, TimeUnit.SECONDS);
        return true;
    }


    @Override
    public void updateRedis(MemberInfo info) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id",info.getMemberId());
        update(info,wrapper);
        MemberInfo memberInfo = baseMapper.selectOne(wrapper);
        redisTemplate.opsForValue().set("member:info:"+info.getMemberId(),JSONArray.toJSONString(memberInfo));
    }

    @Override
    public R verifyPhone(InfoSms infoSms) {
        String apiSms = infoSms.getMsg();
        String sms= redisTemplate.opsForValue().get("member:InfoUpdate:phone:"+infoSms.getMemberPhone());
        if (sms!=null){
            if (apiSms.equals(sms)){
                redisTemplate.delete("member:InfoUpdate:phone:"+infoSms.getMemberPhone());
                return R.ok(true);
            }
            return R.ok("验证码错误",false);
        }
        return R.ok("验证码不存在",false);
    }

    @Transactional
    @Override
    public R updatePassword(Map<String,String> map) {
        MemberInfo info = new MemberInfo();
        String memberId = map.get("memberId");
        info.setMemberId(memberId);
        MemberInfo memberInfo = baseMapper.selectOne(new QueryWrapper<MemberInfo>().eq("member_id",memberId));
        String type=map.get("type");
        String password="";
        if ("0".equals(type)){
            password=DigestUtils.md5DigestAsHex(map.get("newPassword").getBytes());
        }
        if ("1".equals(type)){
            String md5Password = DigestUtils.md5DigestAsHex(map.get("oldPassword").getBytes());
            if (!md5Password.equals(memberInfo.getMemberPassword())){
                return R.fail("密码错误");
            }
            password=DigestUtils.md5DigestAsHex(map.get("newPassword").getBytes());
        }
        if (password.equals("")){
            return R.fail("修改失败");
        }
        info.setMemberPassword(password);
        String s = redisTemplate.opsForValue().get("member:info:" + memberId);
        updateById(info);
        if (s!=null){
            MemberInfo RedisInfo= JSONObject.parseObject(s, MemberInfo.class);
            RedisInfo.setMemberPassword(password);
            redisTemplate.opsForValue().set("member:info:" +  memberId, JSONArray.toJSONString(RedisInfo));
        }
        return R.ok("更新成功",true);
    }

    @Override
    public R verifyPay(InfoSms infoSms) {
        BCryptPasswordEncoder payEncoder = new BCryptPasswordEncoder();
        String s = redisTemplate.opsForValue().get("member:info:" + infoSms.getMemberId());
        MemberInfo memberInfo=null;
        if (s!=null){
            memberInfo = JSONObject.parseObject(s, MemberInfo.class);
        }else {
            memberInfo = getOne(new QueryWrapper<MemberInfo>().eq("member_id", infoSms.getMemberId()));
            redisTemplate.opsForValue().set("member:info:"+infoSms.getMemberId(),JSONArray.toJSONString(memberInfo));
        }
        if (payEncoder.matches(infoSms.getPayPwd(),memberInfo.getPayPwd())){
            return R.ok("验证正确");
        }
        return R.fail("支付密码错误");
    }

    @Override
    public R verifyPayMsg(InfoSms infoSms) {
        String apiSms = infoSms.getMsg();
        String sms= redisTemplate.opsForValue().get("member:InfoUpdate:pay:"+infoSms.getMemberPhone());
        if (sms!=null){
            if (apiSms.equals(sms)){
                redisTemplate.delete("member:InfoUpdate:pay:"+infoSms.getMemberPhone());
                return R.ok(true);
            }
            return R.ok("验证码错误",false);
        }
        return R.ok("验证码不存在",false);
    }

    @Transactional
    @Override
    public R updatePhone(InfoSms infoSms) {
        String apiSms = infoSms.getMsg();
        String sms= redisTemplate.opsForValue().get("member:InfoUpdate:phone:"+infoSms.getMemberPhone());
        if (sms!=null) {
            if (apiSms.equals(sms)) {
                if (checkPhone(infoSms.getMemberPhone())) {
                    return R.ok("电话号码已存在", false);
                } else {
                    String s = redisTemplate.opsForValue().get("member:info:" + infoSms.getMemberId());
                    updateInfoSms(infoSms);
                    if (s!=null){
                        MemberInfo memberInfo= JSONObject.parseObject(s, MemberInfo.class);
                        memberInfo.setMemberPhone(infoSms.getMemberPhone());
                        redisTemplate.opsForValue().set("member:info:" +  memberInfo.getMemberId(), JSONArray.toJSONString(memberInfo));
                    }
                    redisTemplate.delete("member:InfoUpdate:phone:"+infoSms.getMemberPhone());
                    return R.ok("修改成功", true);
                }
            }
            return R.ok("验证码错误", false);
        }
        return R.ok("验证码不存在", false);
    }

    @Transactional
    @Override
    public R updatePay(InfoSms infoSms) {
        BCryptPasswordEncoder payEncoder = new BCryptPasswordEncoder();
        String s = redisTemplate.opsForValue().get("member:info:" + infoSms.getMemberId());
        String newPwd= payEncoder.encode(infoSms.getPayPwd());
        if (s!=null){
            MemberInfo memberInfo = JSONObject.parseObject(s, MemberInfo.class);
            memberInfo.setPayPwd(newPwd);
            redisTemplate.opsForValue().set("member:info:" + memberInfo.getMemberId(), JSONArray.toJSONString(memberInfo));
        }
        infoSms.setPayPwd(newPwd);
        updateInfoSms(infoSms);
        return R.ok("修改成功", true);
    }

    @Transactional
    @Override
    public void updateInfoSms(InfoSms infoSms) {
        MemberInfo memberInfo = new MemberInfo();
        memberInfo.setMemberId(infoSms.getMemberId());
        memberInfo.setPayPwd(infoSms.getPayPwd());
        memberInfo.setMemberPhone(infoSms.getMemberPhone());
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id",infoSms.getMemberId());
        update(memberInfo,wrapper);
    }

    @Override
    public BoostrapDataGrid queryInfo(InfoQueryObject qo) {
        int total=memberInfoMapper.Total(qo);
        return new BoostrapDataGrid(total, total == 0 ? Collections.EMPTY_LIST : memberInfoMapper.infoRows(qo));
    }

    @Override
    public R wxauth(AppWxLoginObject appWxLoginObject) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("wx_openid",appWxLoginObject.getOpenId());
        MemberInfo memberInfo = baseMapper.selectOne(wrapper);
        String token ="";
        if(memberInfo != null){//登录成功
            token= JwtUtils.getJwtToken(String.valueOf(memberInfo.getMemberId()), appWxLoginObject.getType());
            redisTemplate.opsForValue().set("loginToken:"+appWxLoginObject.getType()+":"+memberInfo.getMemberId(),token,7,TimeUnit.DAYS);
            Map map=new HashMap();
            map.put("token",token);
            map.put("nickName",memberInfo.getNickName());
            map.put("avatar",memberInfo.getMemberAvatar());
            map.put("memberAccount",memberInfo.getMemberAccount());
            map.put("email",memberInfo.getMemberEmail());
            map.put("sex",memberInfo.getSex());
            map.put("birthday",memberInfo.getBirthday());
            map.put("address",memberInfo.getAddress());
            map.put("id",memberInfo.getMemberId());
            map.put("password", StringUtils.isEmpty(memberInfo.getMemberPassword())?0 : 1);
            map.put("payPassword",StringUtils.isEmpty(memberInfo.getPayPwd()) ? 0: 1);
            map.put("phone",memberInfo.getMemberPhone());
            map.put("station",memberInfo.getStationId());
            map.put("gradeId",memberInfo.getGradeId());
            map.put("userQrCode",memberInfo.getUserQrCode());
            map.put("bypassAccount",memberInfo.getBypassAccount());
            Object o = redisTemplate.opsForHash().get("member:accounts:info", memberInfo.getMemberId());
            if(o == null){
                MemberAccounts memberAccounts = new MemberAccounts();
                memberAccounts.setMemberId(memberInfo.getMemberId());
                MemberAccounts byId = memberAccountsService.getById(memberAccounts);
                redisTemplate.opsForHash().put("member:accounts:info",memberInfo.getMemberId(),JSON.toJSONString(byId));
            }
         /*   String s = redisTemplate.opsForValue().get("member:info" + memberInfo.getMemberId());
            if(StringUtils.isEmpty(s)){*/
                redisTemplate.opsForValue().set("member:info:" +  memberInfo.getMemberId(), JSONArray.toJSONString(memberInfo));
           /* }*/
            return R.ok(map);
        }else {//用户不存绑定用户
            return R.fail("用户不存在");
        }

    }

    @Override
    public R appeltWxauth(AppWxLoginObject appWxLoginObject) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("member_phone", appWxLoginObject.getPhone());
        MemberInfo memberInfo = baseMapper.selectOne(wrapper);
        String token = "";
        Map map = new HashMap();
        log.info(appWxLoginObject.toString());
        if (memberInfo != null) {//登录成功
            token = JwtUtils.getJwtToken(String.valueOf(memberInfo.getMemberId()), appWxLoginObject.getType());
            redisTemplate.opsForValue().set("loginToken:" + appWxLoginObject.getType() + ":" + memberInfo.getMemberId(), token, 7, TimeUnit.DAYS);
            //查看推荐人名称
            MemberLeaders leadersName = memberLeadersService.findLeadersName(memberInfo.getMemberId());
            if(leadersName != null ){
                QueryWrapper<MemberInfo> wrapperLeader = new QueryWrapper();
                wrapperLeader.eq("member_id", leadersName.getLeaderId());
                MemberInfo leadersMemberInfo = baseMapper.selectOne(wrapperLeader);
                if(leadersMemberInfo !=null ){
                    map.put("leadersName",leadersMemberInfo.getMemberAccount());
                }
            }
            map.put("token", token);
            map.put("nickName", memberInfo.getNickName());
            map.put("avatar", memberInfo.getMemberAvatar());
            map.put("memberAccount", memberInfo.getMemberAccount());
            map.put("email", memberInfo.getMemberEmail());
            map.put("sex", memberInfo.getSex());
            map.put("birthday", memberInfo.getBirthday());
            map.put("address", memberInfo.getAddress());
            map.put("id", memberInfo.getMemberId());
            map.put("password", StringUtils.isEmpty(memberInfo.getMemberPassword()) ? 0 : 1);
            map.put("payPassword", StringUtils.isEmpty(memberInfo.getPayPwd()) ? 0 : 1);
            map.put("phone", memberInfo.getMemberPhone());
            map.put("station", memberInfo.getStationId());
            map.put("gradeId", memberInfo.getGradeId());
            map.put("userQrCode", memberInfo.getUserQrCode());
            map.put("bypassAccount", memberInfo.getBypassAccount());
            map.put("gradeId",memberInfo.getGradeId());
            map.put("starId",memberInfo.getStarId());
            map.put("starOpen",memberInfo.getStarOpen());
            log.info("====WxApplteOpenid:" + memberInfo.getWxApplteOpenid());
            redisTemplate.opsForHash().put("wxApplet:openId:"+appWxLoginObject.getType(), memberInfo.getMemberId(), JSON.toJSONString(appWxLoginObject.getWxApplteOpenid()));
            if (memberInfo.getWxApplteOpenid() == null && "applet".equals(appWxLoginObject.getType())) {
                memberInfo.setWxApplteOpenid(appWxLoginObject.getWxApplteOpenid());
                baseMapper.updateById(memberInfo);
                log.info("====重设WxApplteOpenid====:" + memberInfo.getWxApplteOpenid());
            }
            Object o = redisTemplate.opsForHash().get("member:accounts:info", memberInfo.getMemberId());
            if (o == null) {
                MemberAccounts memberAccounts = new MemberAccounts();
                memberAccounts.setMemberId(memberInfo.getMemberId());
                MemberAccounts byId = memberAccountsService.getById(memberAccounts);
                redisTemplate.opsForHash().put("member:accounts:info", memberInfo.getMemberId(), JSON.toJSONString(byId));
            }
           /* String s = redisTemplate.opsForValue().get("member:info" + memberInfo.getMemberId());
            if (StringUtils.isEmpty(s)) {*/
                redisTemplate.opsForValue().set("member:info:" + memberInfo.getMemberId(), JSONArray.toJSONString(memberInfo));
            /*}*/
            return R.ok(map);
        } else {
            MemberInfo newMember = new MemberInfo();
            newMember.setMemberAvatar(appWxLoginObject.getAvatarUrl());
            newMember.setSex(appWxLoginObject.getGender());
            newMember.setNickName(appWxLoginObject.getNickname());
            newMember.setWxApplteOpenid(appWxLoginObject.getWxApplteOpenid());
            newMember.setMemberAccount(appWxLoginObject.getPhone());
            newMember.setMemberName(appWxLoginObject.getPhone());
            newMember.setMemberGrade("0");
            newMember.setMemberPhone(appWxLoginObject.getPhone());
            newMember.setRegisterTime(new Date());
            newMember.setStationId(null);
            baseMapper.insert(newMember);
            MemberAccounts memberAccounts = new MemberAccounts();
            memberAccounts.setMemberId(newMember.getMemberId());
            memberAccounts.setWhitePearl(new BigDecimal("0"));
            memberAccounts.setMemberPoints(new BigDecimal("0"));
            memberAccounts.setGoldCoupon(0);
            memberAccountsService.save(memberAccounts);
            //插入上下级信息
            log.warn("传过来的邀请码：" + appWxLoginObject.getInvitation());
            if (StringUtils.isBlank(appWxLoginObject.getInvitation()) || "undefined".equals(appWxLoginObject.getInvitation())) {
                appWxLoginObject.setInvitation("1332242670701051905");
            }
            //插入上级 //插入粉丝表
            QueryWrapper<MemberInfo> wrapperm = new QueryWrapper();
            wrapperm.eq("member_id", appWxLoginObject.getInvitation());
            MemberInfo memberInfoNew = baseMapper.selectOne(wrapperm);
            if (memberInfoNew != null) {
                MemberLeaders memberLeaders = new MemberLeaders();
                memberLeaders.setLeaderId(memberInfoNew.getMemberId());
                memberLeaders.setLevelType(1);
                memberLeaders.setMemberId(newMember.getMemberId());
                memberLeadersService.save(memberLeaders);
                MemberFans memberFans = new MemberFans();
                memberFans.setMemberId(memberInfoNew.getMemberId());
                memberFans.setLevelType(1);
                memberFans.setFansId(newMember.getMemberId());
                memberFans.setInviteTime(new Date());
                memberFansService.save(memberFans);
                //判断是否有上上级，插入上上级//插入上上级粉丝表
                QueryWrapper<MemberLeaders> wrapperL = new QueryWrapper();
                wrapperL.eq("member_id", memberInfoNew.getMemberId()).eq("level_type", 1);
                MemberLeaders leaders = memberLeadersService.getOne(wrapperL);
                if (leaders != null) {
                    MemberLeaders memberLeaderst = new MemberLeaders();
                    memberLeaderst.setLeaderId(leaders.getLeaderId());
                    memberLeaderst.setLevelType(2);
                    memberLeaderst.setMemberId(newMember.getMemberId());
                    memberLeadersService.save(memberLeaderst);
                    MemberFans memberFanst = new MemberFans();
                    memberFanst.setMemberId(leaders.getLeaderId());
                    memberFanst.setLevelType(2);
                    memberFanst.setFansId(newMember.getMemberId());
                    memberFanst.setInviteTime(new Date());
                    memberFansService.save(memberFanst);
                }
            }
            token = JwtUtils.getJwtToken(String.valueOf(newMember.getMemberId()), appWxLoginObject.getType());
            redisTemplate.opsForValue().set("loginToken:" + appWxLoginObject.getType() + ":" + newMember.getMemberId(), token, 7, TimeUnit.DAYS);

            //查看推荐人名称
            MemberLeaders leadersName = memberLeadersService.findLeadersName(appWxLoginObject.getInvitation());
            if(leadersName !=null ){
                QueryWrapper<MemberInfo> leaderWrapper = new QueryWrapper();
                leaderWrapper.eq("member_id", leadersName.getLeaderId());
                MemberInfo MemberLeadersInfo = baseMapper.selectOne(leaderWrapper);
                if(MemberLeadersInfo !=null ){
                    map.put("leadersName",MemberLeadersInfo.getMemberAccount());
                }
            }
            map.put("token", token);
            map.put("nickName", newMember.getNickName());
            map.put("avatar", newMember.getMemberAvatar());
            map.put("memberAccount", newMember.getMemberAccount());
            map.put("email", newMember.getMemberEmail());
            map.put("sex", newMember.getSex());
            map.put("birthday", newMember.getBirthday());
            map.put("address", newMember.getAddress());
            map.put("id", newMember.getMemberId());
            map.put("password", StringUtils.isEmpty(newMember.getMemberPassword()) ? 0 : 1);
            map.put("payPassword", StringUtils.isEmpty(newMember.getPayPwd()) ? 0 : 1);
            map.put("phone", newMember.getMemberPhone());
            map.put("station", newMember.getStationId());
            map.put("gradeId", newMember.getGradeId());
            map.put("userQrCode", newMember.getUserQrCode());
            map.put("bypassAccount", newMember.getBypassAccount());
            map.put("gradeId",newMember.getGradeId());
            map.put("starId",0);
            map.put("starOpen",0);
            newMember.setStarId(0);
            newMember.setStarOpen(0);
            redisTemplate.opsForHash().put("wxApplet:openId:"+appWxLoginObject.getType(), newMember.getMemberId(), JSON.toJSONString(appWxLoginObject.getWxApplteOpenid()));
            redisTemplate.opsForHash().put("member:accounts:info", newMember.getMemberId(), JSON.toJSONString(memberAccounts));
            redisTemplate.opsForValue().set("member:info:" + newMember.getMemberId(), JSONArray.toJSONString(newMember));


        }
        return R.ok(map);
    }

    @Override
    public R feignFindMemberInfo(String userId) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("member_id",userId);
        MemberInfo memberInfo = baseMapper.selectOne(wrapper);
        return R.ok(memberInfo);
    }

    @Override
    public MemberInfo FindMemberInfo(String userId) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("member_id",userId);
        return  baseMapper.selectOne(wrapper);
    }

    @Transactional
    @Override
    public R bingMemberStation(Map<String, String> map) {
        String stationId = String.valueOf(map.get("stationId"));
        String type = String.valueOf(map.get("type"));
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        QueryWrapper<MemberInfo> wrapper2 = new QueryWrapper();
        MemberInfo memberInfo = new MemberInfo();
        if ("1".equals(type)) {  //编辑
            wrapper.eq("station_id", stationId).eq("bypass_account", 0);
            String phone = String.valueOf(map.get("Phone"));
            wrapper2.eq("member_account", phone);
            MemberInfo memberInfo1 = memberInfoMapper.selectOne(wrapper2);
            if (memberInfo1 == null) {
                return R.fail("编辑失败,该手机号还没注册账号");
            }
            if (memberInfo1.getBypassAccount() != null && memberInfo1.getBypassAccount() == 1) {
                return R.fail("编辑失败,该账户已经是其他驿站的子账号");
            }
            if(stationId.equals(memberInfo1.getStationId())){
                return R.ok("编辑成功,编辑站长其他信息");
            }
            if (memberInfo1.getBypassAccount() != null && memberInfo1.getBypassAccount() == 0) {
                return R.fail("编辑失败,该账户已经是其他驿站的主账号");
            }
            memberInfo.setStationId(null);
            memberInfo.setBypassAccount(null);
            memberInfoMapper.update(memberInfo, wrapper);
            memberInfo.setStationId(stationId);
            memberInfo.setBypassAccount(0);
            memberInfoMapper.update(memberInfo, wrapper2);
            return R.ok("编辑成功!");
        } else if ("2".equals(type)) {  //添加
            String phone = String.valueOf(map.get("Phone"));
            wrapper2.eq("member_account", phone);
            MemberInfo memberInfo1 = memberInfoMapper.selectOne(wrapper2);
            if (memberInfo1 == null) {
                return R.fail("添加失败,该手机号还没注册账号");
            }
            if (memberInfo1.getBypassAccount() != null && memberInfo1.getBypassAccount() == 0) {
                return R.fail("添加失败,该账户已经是其他驿站的主账号");
            }
            if (memberInfo1.getBypassAccount() != null && memberInfo1.getBypassAccount() == 1) {
                return R.fail("添加失败,该账户已经是其他驿站的子账号");
            }
            memberInfo.setStationId(stationId);
            memberInfo.setBypassAccount(0);
            memberInfoMapper.update(memberInfo, wrapper2);
            return R.ok("添加成功!");
        } else if ("3".equals(type)) {  //删除
            wrapper.eq("station_id", stationId);
            memberInfo.setStationId(null);
            memberInfo.setBypassAccount(null);
            memberInfoMapper.update(memberInfo, wrapper);
            return R.ok("操作成功!");
        }
        return R.ok("绑定失败!");
    }

//    @Override
//    public R createQrCodeById(String memberId,String pic) throws Exception {
//        String s = redisTemplate.opsForValue().get("member:info:" + memberId);
//        MemberInfo memberInfo = JSON.parseObject(s,MemberInfo.class);
//        if (StringUtils.isNotBlank(memberInfo.getUserQrCode())){
//            return R.ok(memberInfo.getUserQrCode());
//        }else {
//            String text = "https://zj.gdwrh.com/fnyg/wxapplet/share?id="+memberId;  //这里设置自定义网站url
      //      String destPath = "\\qrCode\\";
         //  MultipartFile file = QRCodeUtils.encode(text, pic, destPath, true);
//            R r = ossFeign.insertQrFile(file);
//            memberInfo.setUserQrCode(r.getMsg());
//            redisTemplate.opsForValue().set("member:info:" +  memberId, JSONArray.toJSONString(memberInfo));
//            QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
//            wrapper.eq("member_id",memberId);
//            memberInfoMapper.update(memberInfo,wrapper);
//            return R.ok(memberInfo.getUserQrCode());
//        }
//    }

    @Override
    public R createQrCodeByIdNew(String memberId) {
        String s = redisTemplate.opsForValue().get("member:info:" + memberId);
        MemberInfo memberInfo = JSON.parseObject(s, MemberInfo.class);
        if (!StringUtils.isEmpty(memberInfo.getUserQrCode())){
            return R.ok(memberInfo.getUserQrCode());
        }
        String accessToken = null;
        try{
            accessToken = WxQrCode.getAccessToken(wxAuthBean.getAppletId(),wxAuthBean.getAppletSecret());
            String twoCodeUrl = WxQrCode.getminiqrQr(accessToken,"qrCode//",memberId,
                    "pages/my/login/password_login",new Random().nextInt(99999999)+".jpg");
            File file1 = new File(twoCodeUrl);
            FileInputStream fileInputStream = new FileInputStream(file1);
            MultipartFile multipartFile = new MockMultipartFile("copy"+file1.getName(),
                    file1.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);
            R r = ossFeign.insertQrFile(multipartFile,"image");
            if (file1.exists()){
                file1.delete();
            }
            memberInfo.setUserQrCode(r.getMsg());
            redisTemplate.opsForValue().set("member:info:" +  memberId, JSONArray.toJSONString(memberInfo));
            QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
            wrapper.eq("member_id",memberId);
            memberInfoMapper.update(memberInfo,wrapper);
            return R.ok(r.getMsg());
        }catch (Exception e){
            log.error("系统异常:",e);
        }
        return R.fail();
    }

    @Override
    public R queryPersonData(String memberId) {
        String accounts = (String) redisTemplate.opsForHash().get("member:accounts:info", memberId);
        if (StringUtils.isEmpty(accounts)) {
            MemberAccounts memberAccounts = memberAccountsMapper.selectById(memberId);
            redisTemplate.opsForHash().put("member:accounts:info", memberId, JSON.toJSONString(memberAccounts));
            accounts = (String) redisTemplate.opsForHash().get("member:accounts:info", memberId);
        }
        MemberAccounts memberAccounts = JSON.parseObject(accounts, MemberAccounts.class);
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps("fnyg:collect:" +memberId);
        Long size = ops.size();
        R r2 = couponFeign.selectCountByMemberId(memberId);
        Long couponNum = Long.valueOf(String.valueOf(r2.getData()));
        Map<String, Object> map = new HashMap<>();
        map.put("memberAccounts",memberAccounts);
        map.put("size",size);
        map.put("couponNum",couponNum);
        return R.ok(map);
    }

    @Override
    public R addStationSonAccount(Map<String, String> map) {
        String phone = map.get("phone");
        String stationId = map.get("stationId");
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("member_account", phone);
        MemberInfo memberInfo1 = memberInfoMapper.selectOne(wrapper);
        if (memberInfo1 != null) {
            if (memberInfo1.getBypassAccount() == null) {
                MemberInfo memberInfo = new MemberInfo();
                memberInfo.setStationId(stationId);
                memberInfo.setBypassAccount(1);
                memberInfoMapper.update(memberInfo, wrapper);
                return R.ok("添加成功");
            } else if (memberInfo1.getBypassAccount() == 0) {
                return R.fail("很抱歉!，该账号已经是驿站主账号");
            } else if (memberInfo1.getBypassAccount() == 1) {
                return R.fail("很抱歉!，该账号已经是其他驿站子账号");
            }
        }
        return R.fail("该手机号码还没注册!");
    }

    @Override
    public R queryStationSonAccount(String stationId) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("station_id",stationId).ne("bypass_account",0);
        List<MemberInfo> memberInfos = memberInfoMapper.selectList(wrapper);
        return R.ok(memberInfos);
    }

    @Override
    public R deleteStationSonAccount(String phone) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("member_account",phone);
        MemberInfo memberInfo = new MemberInfo();
        memberInfo.setStationId(null);
        memberInfo.setBypassAccount(null);
        memberInfoMapper.update(memberInfo,wrapper);
        return R.ok("移除成功");
    }

    @Override
    public R queryStationMasterById(String stationId) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("station_id", stationId).eq("bypass_account", 0);
        MemberInfo memberInfo = memberInfoMapper.selectOne(wrapper);
        return R.ok(memberInfo != null ? memberInfo.getMemberId() : null);
    }

    @Transactional
    @Override
    public R addLeader(Map<String, String> map) {
        String memberId = map.get("memberId");
        String memberName = map.get("memberName");
        String gradeId = map.get("gradeId");
        String leaderId = map.get("leaderId");
        //添加上级
        if (!StringUtils.isBlank(leaderId)) {
            leaderId = leaderId.trim();
            //1、不能添加自己为上级
            if(leaderId.equals(memberId)){
                return R.fail("不能添加自己为上级!");
            }
            //2、查询该上级Id用户是否存在
            MemberInfo memberInfo = memberInfoMapper.selectById(leaderId);
            if (memberInfo == null) {
                return R.fail("该领导Id的用户不存在");
            }
            //3、查询该上级Id的上级
            QueryWrapper<MemberLeaders> select = new QueryWrapper<>();
            select.eq("member_id", leaderId).eq("level_type", 1);
            MemberLeaders leadersPlus = memberLeadersMapper.selectOne(select);
            if (leadersPlus != null) {
                if(leadersPlus.getLeaderId().equals(memberId)){
                    return R.fail("不能添加粉丝为上级");
                }
                //4、查询该用户的所有粉丝
                QueryWrapper<MemberLeaders> select2 = new QueryWrapper<>();
                select2.eq("leader_id", memberId);
                List<MemberLeaders> memberLeaderss = memberLeadersMapper.selectList(select2);
                if(memberLeaderss!=null && !memberLeaderss.isEmpty()){
                for (MemberLeaders leaders : memberLeaderss) {
                    //5、该用户的粉丝不能是此leaderId用户的上级
                    if (leaders.getMemberId().equals(leadersPlus.getLeaderId())) {
                        return R.fail("该领导Id不可添加为用户的上级");
                    }
                }}
                //6、添加此leaderId用户的上级为memberId用户的上上级
                leadersPlus.setMemberId(memberId);
                leadersPlus.setLevelType(2);
                memberLeadersMapper.insert(leadersPlus);
                MemberFans memberFansPlus = new MemberFans();
                memberFansPlus.setMemberId(leadersPlus.getLeaderId());
                memberFansPlus.setInviteTime(new Date());
                memberFansPlus.setLevelType(2);
                memberFansPlus.setFansName(memberName);
                memberFansPlus.setFansId(memberId);
                memberFansPlus.setFansGrade(Integer.valueOf(gradeId));
                memberFansMapper.insert(memberFansPlus);
            }
            MemberLeaders leaders = new MemberLeaders();
            leaders.setMemberId(memberId);
            leaders.setLevelType(1);
            leaders.setLeaderId(leaderId);
            memberLeadersMapper.insert(leaders);
            MemberFans memberFans = new MemberFans();
            memberFans.setMemberId(leaderId);
            memberFans.setFansId(memberId);
            memberFans.setInviteTime(new Date());
            memberFans.setLevelType(1);
            memberFans.setFansGrade(Integer.valueOf(gradeId));
            memberFans.setFansName(memberName);
            memberFansMapper.insert(memberFans);
            QueryWrapper<MemberFans> wrapper = new QueryWrapper<>();
            wrapper.eq("member_id", memberId).eq("level_type",1);
            List<MemberFans> memberFansTwos = memberFansMapper.selectList(wrapper);
            for (MemberFans memberFansTwo : memberFansTwos) {
                MemberLeaders leadersTwo = new MemberLeaders();
                leadersTwo.setMemberId(memberFansTwo.getFansId());
                leadersTwo.setLevelType(2);
                leadersTwo.setLeaderId(leaderId);
                memberLeadersMapper.insert(leadersTwo);
                memberFansTwo.setMemberId(leaderId);
                memberFansTwo.setLevelType(2);
                memberFansTwo.setInviteTime(new Date());
                memberFansMapper.insert(memberFansTwo);
            }
            return R.ok();
        }
        return R.fail("领导Id不能为空");
    }

    @Override
    public R upgradeVIPs(String memberId) {
        Integer gradeId = memberInfoMapper.queryLevel(memberId);//查询会员等级
        if (gradeId==1){//联盟商家
            return R.fail("您的账号等级已是“联盟商家”不可改为VIP");
        }else  if (gradeId==2){//企业联盟
            return R.fail("您的账号等级已是“企业联盟”不可改为VIP");
        }else if (gradeId==4){//创业vip
            return R.fail("您的账号等级已是“vip”");
        }else {
            memberInfoMapper.ToVip(memberId);
            return R.ok();
        }
    }

    @Override
    public R downgradeFans(String memberId) {
        Integer gradeId = memberInfoMapper.queryLevel(memberId);//查询会员等级
        if (gradeId==1){//联盟商家
            return R.fail("您的账号等级已是“联盟商家”不可降为粉丝");
        }else  if (gradeId==2){//企业联盟
            return R.fail("您的账号等级已是“企业联盟”不可降为粉丝");
        }else if (gradeId==3){//粉丝
            return R.fail("您的账号等级已是“粉丝”");
        }else {
            memberInfoMapper.becomeAFan(memberId);
            return R.ok();
        }
    }



    @Override
    public List<MemberInfo> queryInfoRedis(HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        String s = redisTemplate.opsForValue().get("member:info:" + id);
        if (StringUtils.isNotBlank(s)){
            List<MemberInfo> infoList = JSON.parseArray(s, MemberInfo.class);
            return infoList;
        }else {
            QueryWrapper<MemberInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("member_id",id);
            List<MemberInfo> infoList = list(wrapper);
            redisTemplate.opsForValue().set("member:info:" + id, JSONArray.toJSONString(infoList));
            return infoList;
        }
    }

    @Override
    public R appCodePhone(AppWxLoginObject appWxLoginObject) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("member_phone",appWxLoginObject.getPhone());
        MemberInfo memberInfo = baseMapper.selectOne(wrapper);
        String token="";
        if(memberInfo != null){//登录成功
            token=JwtUtils.getJwtToken(String.valueOf(memberInfo.getMemberId()), appWxLoginObject.getType());
            redisTemplate.opsForValue().set("loginToken:"+appWxLoginObject.getType()+":"+memberInfo.getMemberId(),token,7,TimeUnit.DAYS);
            Map map=new HashMap();
            map.put("token",token);
            map.put("nickName",memberInfo.getNickName());
            map.put("avatar",memberInfo.getMemberAvatar());
            map.put("memberAccount",memberInfo.getMemberAccount());
            map.put("email",memberInfo.getMemberEmail());
            map.put("sex",memberInfo.getSex());
            map.put("birthday",memberInfo.getBirthday());
            map.put("address",memberInfo.getAddress());
            map.put("id",memberInfo.getMemberId());
            map.put("password",StringUtils.isEmpty(memberInfo.getMemberPassword())?0 : 1);
            map.put("payPassword",StringUtils.isEmpty(memberInfo.getPayPwd()) ? 0: 1);
            map.put("phone",memberInfo.getMemberPhone());
            map.put("station",memberInfo.getStationId());
            map.put("gradeId",memberInfo.getGradeId());
            map.put("userQrCode",memberInfo.getUserQrCode());
            map.put("bypassAccount",memberInfo.getBypassAccount());
            Object o = redisTemplate.opsForHash().get("member:accounts:info", memberInfo.getMemberId());
            if(o == null){
                MemberAccounts memberAccounts = new MemberAccounts();
                memberAccounts.setMemberId(memberInfo.getMemberId());
                MemberAccounts byId = memberAccountsService.getById(memberAccounts);
                redisTemplate.opsForHash().put("member:accounts:info",memberInfo.getMemberId(),JSON.toJSONString(byId));
            }
         /*   String s = redisTemplate.opsForValue().get("member:info" + memberInfo.getMemberId());
            if(StringUtils.isEmpty(s)){*/
                redisTemplate.opsForValue().set("member:info:" +  memberInfo.getMemberId(), JSONArray.toJSONString(memberInfo));
           /* }*/
            return R.ok(map);
        }else {//用户不存绑定用户
            return R.fail("用户不存在");
        }
    }

    @Override
    public R appPassPhone(AppWxLoginObject appWxLoginObject) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("member_account",appWxLoginObject.getPhone());
        MemberInfo memberInfo = baseMapper.selectOne(wrapper);
        String token="";
        if(memberInfo != null){//登录成功
           // BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
           // boolean matches = passwordEncoder.matches(appWxLoginObject.getPassword(), memberInfo.getMemberPassword());
            String md5Password = DigestUtils.md5DigestAsHex(appWxLoginObject.getPassword().getBytes());
            if(memberInfo.getMemberPassword() == null || !md5Password.equals(memberInfo.getMemberPassword())){
                return R.fail("密码错误");
            }
            token=JwtUtils.getJwtToken(String.valueOf(memberInfo.getMemberId()), appWxLoginObject.getType());
            redisTemplate.opsForValue().set("loginToken:"+appWxLoginObject.getType()+":"+memberInfo.getMemberId(),token,7,TimeUnit.DAYS);
            Map map=new HashMap();
            map.put("token",token);
            map.put("nickName",memberInfo.getNickName());
            map.put("avatar",memberInfo.getMemberAvatar());
            map.put("memberAccount",memberInfo.getMemberAccount());
            map.put("email",memberInfo.getMemberEmail());
            map.put("sex",memberInfo.getSex());
            map.put("birthday",memberInfo.getBirthday());
            map.put("address",memberInfo.getAddress());
            map.put("id",memberInfo.getMemberId());
            map.put("password",StringUtils.isEmpty(memberInfo.getMemberPassword())?0 : 1);
            map.put("payPassword",StringUtils.isEmpty(memberInfo.getPayPwd()) ? 0: 1);
            map.put("phone",memberInfo.getMemberPhone());
            map.put("station",memberInfo.getStationId());
            map.put("gradeId",memberInfo.getGradeId());
            map.put("userQrCode",memberInfo.getUserQrCode());
            map.put("bypassAccount",memberInfo.getBypassAccount());
            Object o = redisTemplate.opsForHash().get("member:accounts:info", memberInfo.getMemberId());
            if(o == null){
                MemberAccounts memberAccounts = new MemberAccounts();
                memberAccounts.setMemberId(memberInfo.getMemberId());
                MemberAccounts byId = memberAccountsService.getById(memberAccounts);
                redisTemplate.opsForHash().put("member:accounts:info",memberInfo.getMemberId(),JSON.toJSONString(byId));
            }
           /* String s = redisTemplate.opsForValue().get("member:info" + memberInfo.getMemberId());
            if(StringUtils.isEmpty(s)){*/
                redisTemplate.opsForValue().set("member:info:" +  memberInfo.getMemberId(), JSONArray.toJSONString(memberInfo));
           /* }*/
            return R.ok(map);
        }else {//用户不存绑定用户
            return R.fail("用户不存在");
        }

    }

    @Transactional
    @Override
    public R bindWx(AppWxLoginObject appWxLoginObject) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("member_phone",appWxLoginObject.getPhone());
        MemberInfo memberInfo = baseMapper.selectOne(wrapper);
        String token="";
        if(memberInfo != null){
            memberInfo.setWxOpenid(appWxLoginObject.getOpenId());
            baseMapper.updateById(memberInfo);
            token=JwtUtils.getJwtToken(String.valueOf(memberInfo.getMemberId()), appWxLoginObject.getType());
            redisTemplate.opsForValue().set("loginToken:"+appWxLoginObject.getType()+":"+memberInfo.getMemberId(),token,7,TimeUnit.DAYS);
            Map map=new HashMap();
            map.put("token",token);
            map.put("nickName",memberInfo.getNickName());
            map.put("avatar",memberInfo.getMemberAvatar());
            map.put("memberAccount",memberInfo.getMemberAccount());
            map.put("email",memberInfo.getMemberEmail());
            map.put("sex",memberInfo.getSex());
            map.put("birthday",memberInfo.getBirthday());
            map.put("address",memberInfo.getAddress());
            map.put("id",memberInfo.getMemberId());
            map.put("password",StringUtils.isEmpty(memberInfo.getMemberPassword())?0 : 1);
            map.put("payPassword",StringUtils.isEmpty(memberInfo.getPayPwd()) ? 0: 1);
            map.put("phone",memberInfo.getMemberPhone());
            map.put("station",memberInfo.getStationId());
            map.put("gradeId",memberInfo.getGradeId());
            map.put("userQrCode",memberInfo.getUserQrCode());
            map.put("bypassAccount",memberInfo.getBypassAccount());
            String o = (String) redisTemplate.opsForHash().get("member:accounts:info", memberInfo.getMemberId());
            if(StringUtils.isEmpty(o)){
                MemberAccounts memberAccounts = new MemberAccounts();
                memberAccounts.setMemberId(memberInfo.getMemberId());
                MemberAccounts byId = memberAccountsService.getById(memberAccounts);
                redisTemplate.opsForHash().put("member:accounts:info",memberInfo.getMemberId(),JSON.toJSONString(byId));
            }
          /*  String s = redisTemplate.opsForValue().get("member:info" + memberInfo.getMemberId());
            if(StringUtils.isEmpty(s)){*/
                redisTemplate.opsForValue().set("member:info:" +  memberInfo.getMemberId(), JSONArray.toJSONString(memberInfo));
            /*}*/
            return R.ok(map);
        }else{
            MemberInfo newMember = new MemberInfo();
            newMember.setMemberAvatar(appWxLoginObject.getAvatarUrl());
            newMember.setSex(appWxLoginObject.getGender());
            newMember.setNickName(appWxLoginObject.getNickname());
            newMember.setWxOpenid(appWxLoginObject.getOpenId());
            newMember.setMemberAccount(appWxLoginObject.getPhone());
            newMember.setMemberName(appWxLoginObject.getPhone());
            newMember.setMemberGrade("0");
            newMember.setMemberPhone(appWxLoginObject.getPhone());
            newMember.setRegisterTime(new Date());
            newMember.setStationId(null);
            baseMapper.insert(newMember);
            MemberAccounts memberAccounts = new MemberAccounts();
            memberAccounts.setMemberId(newMember.getMemberId());
            memberAccountsService.save(memberAccounts);
            if (StringUtils.isBlank(appWxLoginObject.getInvitation()) || "undefined".equals(appWxLoginObject.getInvitation())) {
                appWxLoginObject.setInvitation("13149329491");
            }
            //插入上级 //插入粉丝表
            QueryWrapper<MemberInfo> wrapperm = new QueryWrapper();
            wrapperm.eq("member_phone", appWxLoginObject.getInvitation());
            MemberInfo memberInfoNew = baseMapper.selectOne(wrapperm);
            if (memberInfoNew != null) {
                MemberLeaders memberLeaders = new MemberLeaders();
                memberLeaders.setLeaderId(memberInfoNew.getMemberId());
                memberLeaders.setLevelType(1);
                memberLeaders.setMemberId(newMember.getMemberId());
                memberLeadersService.save(memberLeaders);
                MemberFans memberFans = new MemberFans();
                memberFans.setMemberId(memberInfoNew.getMemberId());
                memberFans.setLevelType(1);
                memberFans.setFansId(newMember.getMemberId());
                memberFans.setInviteTime(new Date());
                memberFansService.save(memberFans);
                //判断是否有上上级，插入上上级//插入上上级粉丝表
                QueryWrapper<MemberLeaders> wrapperL = new QueryWrapper();
                wrapperL.eq("member_id", memberInfoNew.getMemberId()).eq("level_type", 1);
                MemberLeaders leaders = memberLeadersService.getOne(wrapperL);
                if (leaders != null) {
                    MemberLeaders memberLeaderst = new MemberLeaders();
                    memberLeaderst.setLeaderId(leaders.getLeaderId());
                    memberLeaderst.setLevelType(2);
                    memberLeaderst.setMemberId(newMember.getMemberId());
                    memberLeadersService.save(memberLeaderst);
                    MemberFans memberFanst = new MemberFans();
                    memberFanst.setMemberId(leaders.getLeaderId());
                    memberFanst.setLevelType(2);
                    memberFanst.setFansId(newMember.getMemberId());
                    memberFanst.setInviteTime(new Date());
                    memberFansService.save(memberFanst);
                }
            }
            token=JwtUtils.getJwtToken(String.valueOf(newMember.getMemberId()), appWxLoginObject.getType());
            redisTemplate.opsForValue().set("loginToken:"+appWxLoginObject.getType()+":"+newMember.getMemberId(),token,7,TimeUnit.DAYS);
            Map map=new HashMap();
            map.put("token",token);
            map.put("nickName",newMember.getNickName());
            map.put("avatar",newMember.getMemberAvatar());
            map.put("memberAccount",newMember.getMemberAccount());
            map.put("email",newMember.getMemberEmail());
            map.put("sex",newMember.getSex());
            map.put("birthday",newMember.getBirthday());
            map.put("address",newMember.getAddress());
            map.put("id",newMember.getMemberId());
            map.put("password",StringUtils.isEmpty(newMember.getMemberPassword())?0 : 1);
            map.put("payPassword",StringUtils.isEmpty(newMember.getPayPwd()) ? 0: 1);
            map.put("phone",newMember.getMemberPhone());
            map.put("station",newMember.getStationId());
            map.put("gradeId",newMember.getGradeId());
            map.put("userQrCode",newMember.getUserQrCode());
            map.put("bypassAccount",newMember.getBypassAccount());
            redisTemplate.opsForHash().put("member:accounts:info",newMember.getMemberId(),JSON.toJSONString(memberAccounts));
            redisTemplate.opsForValue().set("member:info:" +  newMember.getMemberId(), JSONArray.toJSONString(newMember));
            return R.ok(map);
        }
    }

    @Override
    public Boolean checkPhone(String phone) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("member_phone",phone);
        MemberInfo memberInfo = baseMapper.selectOne(wrapper);
        return memberInfo !=null ? true: false;
    }

    @Override
    public MemberInfo findByPhone(String phone) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("member_phone",phone);
       return baseMapper.selectOne(wrapper);
    }

    @Override
    @Transactional
    @RepeatSubmit
    public R register(AppWxLoginObject appWxLoginObject) {
        //BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        MemberInfo newMember = new MemberInfo();
        // newMember.setMemberPassword(passwordEncoder.encode(appWxLoginObject.getPassword()));
        String md5Password = DigestUtils.md5DigestAsHex(appWxLoginObject.getPassword().getBytes());
        newMember.setMemberPassword(md5Password);
        newMember.setMemberAccount(appWxLoginObject.getPhone());
        newMember.setMemberName(appWxLoginObject.getPhone());
        newMember.setMemberGrade("0");
        newMember.setMemberPhone(appWxLoginObject.getPhone());
        newMember.setRegisterTime(new Date());
        baseMapper.insert(newMember);
        MemberAccounts memberAccounts = new MemberAccounts();
        memberAccounts.setMemberId(newMember.getMemberId());
        memberAccountsService.save(memberAccounts);
        //插入上下级信息
        if (StringUtils.isBlank(appWxLoginObject.getInvitation()) || "undefined".equals(appWxLoginObject.getInvitation()) ) {
            appWxLoginObject.setInvitation("13149329491");
        }
        //插入上级 //插入粉丝表
        QueryWrapper<MemberInfo> wrapperm = new QueryWrapper();
        wrapperm.eq("member_phone", appWxLoginObject.getInvitation());
        MemberInfo memberInfoNew = baseMapper.selectOne(wrapperm);
        if (memberInfoNew != null) {
            MemberLeaders memberLeaders = new MemberLeaders();
            memberLeaders.setLeaderId(memberInfoNew.getMemberId());
            memberLeaders.setLevelType(1);
            memberLeaders.setMemberId(newMember.getMemberId());
            memberLeadersService.save(memberLeaders);
            MemberFans memberFans = new MemberFans();
            memberFans.setMemberId(memberInfoNew.getMemberId());
            memberFans.setLevelType(1);
            memberFans.setFansId(newMember.getMemberId());
            memberFans.setInviteTime(new Date());
            memberFansService.save(memberFans);
            //判断是否有上上级，插入上上级//插入上上级粉丝表
            QueryWrapper<MemberLeaders> wrapperL = new QueryWrapper();
            wrapperL.eq("member_id", memberInfoNew.getMemberId()).eq("level_type", 1);
            MemberLeaders leaders = memberLeadersService.getOne(wrapperL);
            if (leaders != null) {
                MemberLeaders memberLeaderst = new MemberLeaders();
                memberLeaderst.setLeaderId(leaders.getLeaderId());
                memberLeaderst.setLevelType(2);
                memberLeaderst.setMemberId(newMember.getMemberId());
                memberLeadersService.save(memberLeaderst);
                MemberFans memberFanst = new MemberFans();
                memberFanst.setMemberId(leaders.getLeaderId());
                memberFanst.setLevelType(2);
                memberFanst.setFansId(newMember.getMemberId());
                memberFanst.setInviteTime(new Date());
                memberFansService.save(memberFanst);
            }
        }
        return R.ok("注册成功");
    }

    @Override
    public R appUpdatePass(AppWxLoginObject appWxLoginObject) {
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("member_phone",appWxLoginObject.getPhone());
        MemberInfo memberInfo = baseMapper.selectOne(wrapper);
     //   BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
      //  memberInfo.setMemberPassword(passwordEncoder.encode(appWxLoginObject.getPassword()));
        String md5Password = DigestUtils.md5DigestAsHex(appWxLoginObject.getPassword().getBytes());
        memberInfo.setMemberPassword(md5Password);
        baseMapper.updateById(memberInfo);
        return R.ok("修改成功");
    }

    @Override
    public R registerHtml(RegisterInfo registerInfo) {
        QueryWrapper<MemberInfo> one = new QueryWrapper();
        one.eq("member_phone", registerInfo.getPhone());
        MemberInfo memberInfo1 = baseMapper.selectOne(one);
        if (memberInfo1 != null) {
            return R.fail("该号码已存在");
        }
        MemberInfo newMember = new MemberInfo();
        String md5Password = DigestUtils.md5DigestAsHex(registerInfo.getPassword().getBytes());
        newMember.setMemberPassword(md5Password);
        newMember.setMemberAccount(registerInfo.getPhone());
        newMember.setMemberName(registerInfo.getPhone());
        newMember.setMemberGrade("0");
        newMember.setMemberPhone(registerInfo.getPhone());
        newMember.setRegisterTime(new Date());
        baseMapper.insert(newMember);
        MemberAccounts memberAccounts = new MemberAccounts();
        memberAccounts.setMemberId(newMember.getMemberId());
        memberAccounts.setWhitePearl(new BigDecimal("0"));
        memberAccounts.setMemberPoints(new BigDecimal("0"));
        memberAccounts.setGoldCoupon(0);
        memberAccountsService.save(memberAccounts);
        //插入上下级信息
        if (StringUtils.isBlank(registerInfo.getInvitation())) {
            registerInfo.setInvitation("13149329491");
        }
        //插入上级 //插入粉丝表
        QueryWrapper<MemberInfo> wrapper = new QueryWrapper();
        wrapper.eq("member_phone", registerInfo.getInvitation());
        MemberInfo memberInfo = baseMapper.selectOne(wrapper);
        if (memberInfo != null) {
            MemberLeaders memberLeaders = new MemberLeaders();
            memberLeaders.setLeaderId(memberInfo.getMemberId());
            memberLeaders.setLevelType(1);
            memberLeaders.setMemberId(newMember.getMemberId());
            memberLeadersService.save(memberLeaders);
            MemberFans memberFans = new MemberFans();
            memberFans.setMemberId(memberInfo.getMemberId());
            memberFans.setLevelType(1);
            memberFans.setFansId(newMember.getMemberId());
            memberFans.setInviteTime(new Date());
            memberFansService.save(memberFans);
            //判断是否有上上级，插入上上级//插入上上级粉丝表
            QueryWrapper<MemberLeaders> wrapperL = new QueryWrapper();
            wrapperL.eq("member_id", memberInfo.getMemberId()).eq("level_type", 1);
            MemberLeaders leaders = memberLeadersService.getOne(wrapperL);
            if (leaders != null) {
                MemberLeaders memberLeaderst = new MemberLeaders();
                memberLeaderst.setLeaderId(leaders.getLeaderId());
                memberLeaderst.setLevelType(2);
                memberLeaderst.setMemberId(newMember.getMemberId());
                memberLeadersService.save(memberLeaderst);
                MemberFans memberFanst = new MemberFans();
                memberFanst.setMemberId(leaders.getLeaderId());
                memberFanst.setLevelType(2);
                memberFanst.setFansId(newMember.getMemberId());
                memberFanst.setInviteTime(new Date());
                memberFansService.save(memberFanst);
            }
        }

        return R.ok("注册成功");
    }


    //会员消费累计金额
    public void addConsume(String userId,BigDecimal amount){
        memberInfoMapper.addConsume(userId,amount);

    }


}
